//
//  TableViewCell.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/29.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import Foundation
import WisdomHUD

enum LGTRWZDetailBtnType:Int{
    case LookBtnType = 0  //查看单价
    case RePublicBtnType = 1 //重新发布
    case StopBtnType = 2 //暂停
    case RebackBtnType = 3 //撤回
    case AddBtnType = 4 //追加
    case ModifyBtnType = 5 //修改
    case GoOnBtnType = 6 //追加
    case PublicBtnType = 7 //发布
    case MoreBtnType = 8 //更多
    case TaskApplyType = 9 //申请任务
    case TaskSubmitType = 10 //提交按钮
    case OrderGiveUPType = 11 //任务放弃提交
    case OrderSubmitType = 12 //订单提交按钮
    case ApplyBegType = 13 //申请申诉
    case ApplyGotoType = 14 //申请介入
    case RWZRefuseType = 15 //拒绝
    case RWZPassType = 16 //通过
}

extension LGTPostDetailVC{
    //数据转换
    func taskInfoChangeSubmitInfo(json:Dictionary<String, Any>){
        let info:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
        let viewInfo:Dictionary<String, Any> = info["view"] as? Dictionary<String, Any> ?? [:]
        let usetInfo:Dictionary<String, Any> = info["user_info"] as? Dictionary<String, Any> ?? [:]
        let userModel:UserModel = try! lgtDecode(UserModel.self, param: usetInfo)
        self.userModel = userModel
        self.submitDataInfo2["id"] = info["id"]
        self.submitDataInfo2["projectName"] = info["title"] as? String ?? ""
        self.submitDataInfo2["taskRequest"] = info["content"] as? String ?? ""
        self.submitDataInfo2["commission_rate"] = info["commission"]
        self.submitDataInfo2["deposit_rate"] = info["deposit_rate"]
        self.is_isset = info["is_isset"] as? Int ?? 0
        
        let price:Int = info["price"] as? Int ?? 0
        //多少钱一单
        self.submitDataInfo2["workPrice"] = "\(Double(price) / 100.0)"
        //还剩余多少次
        self.submitDataInfo2["taskCount"] = "\(info["free_count"] as? Int ?? 0)"
        //类型
        var typeModel:PostNameModel = PostNameModel()
        typeModel.name = viewInfo["type"] as? String ?? ""
        self.submitDataInfo2["type"] = typeModel
        //系统
        var osModel:PostNameModel = PostNameModel()
        osModel.name = viewInfo["os"] as? String ?? ""
        self.submitDataInfo2["os"] = osModel
        //置顶天数
        self.submitDataInfo2["toptime"] = info["top_time"] as? String ?? ""
        //做单时间
        var workTimeModel:PostNameModel = PostNameModel()
        workTimeModel.name = viewInfo["complete_time_limit"] as? String ?? ""
        self.submitDataInfo2["workTime"] = workTimeModel
        //做单次数
        var workTimesModel:PostNameModel = PostNameModel()
        workTimesModel.name = viewInfo["frequency"] as? String ?? ""
        self.submitDataInfo2["workTimes"] = workTimesModel
        //审核时间
        var reviewModel:PostNameModel = PostNameModel()
        reviewModel.name = viewInfo["review_time_limit"] as? String ?? ""
        self.submitDataInfo2["reviewTime"] = reviewModel
        //结束时间
        let offline:String = info["end_time"] as? String ?? ""
        self.submitDataInfo2["offline"] = offline
        //总价
        self.submitDataInfo2["payMoney"] =  "\(Double(info["amount"] as? Int ?? 0) / 100.0)元"
        
        //最顶部视图参数
        var topParam:Dictionary<String, Any> = [:]
        topParam["free_count"] = "\(info["free_count"] as? Int ?? 0)"
        topParam["success_count"] = "\(info["success_count"] as? Int ?? 0)"
        topParam["offline"] = offline
        topParam["isTop"] = true
        topParam["order_statistics_list"] = viewInfo["order_statistics_list"]
        topParam["status"] = info["status"]
        self.topParam = topParam
        
        //步骤
        let stepStr:String =  info["params"] as? String ?? ""
        var stepInfo:Dictionary<String, Any> = BaseUtil.baseUtil.getDictionaryFromJSONString(jsonString: stepStr)
        //操作记录
        self.timeStepArray = stepInfo["time_step"] as? Array<Dictionary<String, Any>> ?? []
        let stepArray:Array<Dictionary<String, Any>> = stepInfo["step"] as? Array<Dictionary<String, Any>> ?? []
        self.stepArray = stepArray
        var newStepArray:Array<Dictionary<String, Any>> = []
        if stepArray.count > 0{
            for i in 0..<stepArray.count{
                let d:Dictionary<String, Any> = stepArray[i]
                let stepText:String = d["title"] as? String ?? ""
                let subText:String = d["message"] as? String ?? ""
                var newData:Dictionary<String, Any> = ["stepText":stepText,
                                                       "subText":subText]
                //image
                let imageInfo:Dictionary<String, Any> = d["image"] as? Dictionary<String, Any> ?? [:]
                let url:String = imageInfo["url"] as? String ?? "'"
                let selectInfo:Dictionary<String, Any> = ["url":url]
                newData["selectInfo"] = selectInfo
                let type:Int = d["type"] as? Int ?? 0
                //type 状态[1-审核中,2-未通过,3-派发中,4-暂停中,5-已撤回,6-已过期,7-已完成,8-已下架] ,
                switch type{
                case 1:
                    newData["isurl"] = true
                    break
                case 2:
                    newData["imageAndText"] = true
                    newData["type"] = 2
                    break
                case 3:
                    newData["copy"] = true
                    break
                case 4:
                    newData["imageAndText"] = true
                    newData["type"] = 1
                    break
                case 5:
                    newData["imageAndText"] = true
                    newData["type"] = 0
                    break
                case 6:
                    newData["collection"] = true
                    break
                default:
                    break
                }
                newData["canEdit"] = self.canEdit
                newStepArray.append(newData)
            }
            self.submitDataInfo2["step"] = newStepArray
        }
    }


    //初始化数据
    func initData(reload:Bool=true){
        //用户信息
        let projectName = self.submitDataInfo2["projectName"] as? String ?? ""
        let workPrice = Double(self.submitDataInfo2["workPrice"] as? String ?? "") ?? 0.0
        let workPriceStr:String = "¥\(workPrice)"
        let taskCountStr:String = " 余\(self.submitDataInfo2["taskCount"] as? String ?? "")次  "
        let typeStr:String =  " \((self.submitDataInfo2["type"] as? PostNameModel)?.name ?? "")  "
        let osStr:String =  " \((self.submitDataInfo2["os"] as? PostNameModel)?.name ?? "")  "
        
        //基本信息
        let workTimes:String = (self.submitDataInfo2["workTimes"] as? PostNameModel)?.name ?? "" //任务次数
        let reviewTime:String = (self.submitDataInfo2["reviewTime"] as? PostNameModel)?.name ?? "" //审核时间
        let workTime:String = (self.submitDataInfo2["workTime"] as? PostNameModel)?.name ?? "" // 做单时间
        let offline:String = self.submitDataInfo2["offline"]  as? String ?? "" //做单次数
        let topTime:Int = Int(self.submitDataInfo2["toptime"] as? String ?? "") ?? 0 //置顶天数
        let topTimeStr = "\(topTime)天"
        
        //if self.isPreview == false{
        if self.viewDetailType != .RWZ_PreView_Type{
            let payStr:String = self.submitDataInfo2["payMoney"] as? String ?? ""
            self.infoData = [
                         "workTime":workTime,
                         "offline":offline,
                         "workTimes":workTimes,
                         "reviewTime":reviewTime,
                         "topTimeStr": topTimeStr,
                         "payMoney":payStr,
                         "taskCountStr": "\(self.submitDataInfo2["taskCount"] as? String ?? "")次",
                         "workPrice":"\(workPrice)元/每次"]
        }
        
        //任务要求
        let taskRequest = self.submitDataInfo2["taskRequest"] as? String ?? ""
        self.data = [
                    [["projectName":projectName,
                      "workPriceStr":workPriceStr,
                      "taskCountStr":taskCountStr,
                      "typeStr":typeStr,
                      "osStr":osStr, "isUserInfo":true,
                      "name": self.userModel?.nickname ?? "",
                      "userUrl":self.userModel?.avatar?.url ?? ""
                        ]],
                     [["topTimeStr": topTimeStr,
                         "workTime":workTime,
                         "offline":offline,
                         "workTimes":workTimes,
                         "reviewTime":reviewTime,
                         "isTaskInfo":true]],
                     [["taskRequest": taskRequest,
                         "isRequest":true
                        ]]
                     ]
        
        //有顶部视图 是任务主的界面有
        //if self.topParam != nil && self.isRWZ == true{
        if self.topParam != nil && self.viewDetailType == .RWZ_Task_Detail_Type{
            self.data.insert([self.topParam!], at: 0)
        }
        
        //订单状态视图
        if self.viewDetailType == .RWZ_OrderView_Type || self.viewDetailType == .LLZ_OrderView_Type{
            self.data.insert([["isOrder":true]], at: 0)
        }
        
        var stepArray:Array<Dictionary<String, Any>> = self.submitDataInfo2["step"] as? Array<Dictionary<String, Any>> ?? []
        if stepArray.count > 0{
            for i in 0..<stepArray.count{
                var d = stepArray[i]
                d["canEdit"] = self.canEdit
                if self.viewDetailType == DetailType.LLZ_OrderView_Type{
                    let key:String = "\(i + 1)"
                    let submitInfo = self.orderSubmitInfo[key]
                    if submitInfo != nil{
                        //提交过程的参数显示
                        d["submitInfo"] = submitInfo
                    }
                }
                stepArray[i] = d
            }
            
            stepArray.insert(["stepHead": true], at: 0)
            self.data.insert(stepArray, at: self.data.count)
        }
        
        //是否需要刷新数据
        if reload == true{
            self.tableView?.reloadData()
        }
        
        self.footerView?.isHidden = false
        //初始化底部视图
        self.initFooterView()
    }
    
    
    //初始化视图
    func initFooterView(){
        let viewArray = self.footerView!.subviews
        for i in 0..<viewArray.count{
            let subView:UIView = viewArray[i]
            subView.removeFromSuperview()
        }
        //流量主订单底部视图
        if self.viewDetailType == .LLZ_OrderView_Type{
            self.initLLZOrderFooterView()
            return
        }
        //任务主订单底部视图
        if self.viewDetailType == .RWZ_OrderView_Type{
            self.initRWZOrderViewType()
            return
        }
        //  流量主 任务视图
        if self.viewDetailType == .LLZ_Task_Detail_Type{
            self.initLLZTaskDetailFooterView()
            return
        }
        //预览视图
        if  self.viewDetailType == .RWZ_PreView_Type{
            self.initPreViewFooterView()
            return
        }
        //任务主任务视图
        self.initRWZTaskDetailFooterView()
    }
    
    @objc func postAction(sender:UIButton){
        switch sender.tag {
            //查看单价
        case LGTRWZDetailBtnType.LookBtnType.rawValue:
            self.footMoreView?.isHidden = true
            print("查看单价")
            self.lookPrice()
            break
            //重新发布
        case LGTRWZDetailBtnType.RePublicBtnType.rawValue:
            print("重新发布")
            break
            //暂停
        case LGTRWZDetailBtnType.StopBtnType.rawValue:
            print("暂停")
            self.updateTaskStatues(status: 4)
            break
            //撤回
        case LGTRWZDetailBtnType.RebackBtnType.rawValue:
            print("撤回")
            self.footMoreView?.isHidden = true
            self.updateTaskStatues(status: 5)
            break
        //修改
        case LGTRWZDetailBtnType.ModifyBtnType.rawValue:
            print("修改")
            //if self.isPreview == true{
            if self.viewDetailType == .RWZ_PreView_Type{
                self.navigationController?.popViewController(animated: true)
            }
            break
            //追加
        case LGTRWZDetailBtnType.AddBtnType.rawValue:
            print("追加")
            self.appendAction()
            break
        //继续
        case LGTRWZDetailBtnType.GoOnBtnType.rawValue:
            print("继续")
            self.updateTaskStatues(status: 3)
            break
            // 发布
        case LGTRWZDetailBtnType.PublicBtnType.rawValue:
            print("发布")
            break
            // 更多
        case LGTRWZDetailBtnType.MoreBtnType.rawValue:
            print("更多")
            self.showFooterMoreView()
            break
            //提交任务
        case LGTRWZDetailBtnType.TaskSubmitType.rawValue:
            self.submitTask()
            break
           
            //申请任务
        case LGTRWZDetailBtnType.TaskApplyType.rawValue:
            self.applyTask()
            break
            //任务放弃提交
        case LGTRWZDetailBtnType.OrderGiveUPType.rawValue:
            self.giveupTask()
            break
            //订单提交按钮
        case LGTRWZDetailBtnType.OrderSubmitType.rawValue:
            self.submitTask()
            break
            //申请申诉
        case LGTRWZDetailBtnType.ApplyBegType.rawValue:
            self.begTask()
            break
            //申请介入
        case LGTRWZDetailBtnType.ApplyGotoType.rawValue:
            self.applyGoto()
            break
            //拒绝
        case LGTRWZDetailBtnType.RWZRefuseType.rawValue:
            self.refuse()
            break
           //通过
        case LGTRWZDetailBtnType.RWZPassType.rawValue:
            self.pass()
            break
            
        default:
            break
        }
    }
    
    //显示弹窗
    func showAlerView(title:String, desc:String, subText:String, sureTitle:String="确认", cancelTitle:String="取消", sureBlock:@escaping ClickBlock, cancelBlock:@escaping ClickBlock){
        LGTRWZCommenAlert.CommenAlertalertShow(title: title, desc: desc, subText: subText, sureTitle: sureTitle, cancelTitle: cancelTitle, sureBlock:sureBlock, cancelBlock: cancelBlock, currentVC: self.navigationController!)
    }
    
    //网络请求
    func orderAction(url:String, param:Dictionary<String, Any>){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: url, param: param, showMessage: true, success: { (json) in
            weakSelf?.dataChange(json: json)
        }) { (json) in
        }
    }
    
    //通过
    func pass(){
        weak var weakSelf = self
        self.showAlerView(title: "温馨提示", desc: "您确定要通过此任务单吗？", subText: "确认后佣金将转给该用户", sureBlock: {
            let param:Dictionary<String, Any> = ["id":weakSelf?.orderModel?.id ?? 0, "status":5]
            self.orderAction(url: RWZ_OrderStatus_Update_URL, param: param)
        }) {
            
        }
    }
    
    //拒绝
    func refuse(){
        let vc:LGTRefuseAlertVC = LGTRefuseAlertVC()
        vc.clickInfoBlock = updateOrderBlock
        vc.orderModel = self.orderModel
        vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: false, completion: nil)
    }
    
    func applyGoto(){
        
    }
    
    func begTask(){
        
    }
    
    //放弃任务
    func giveupTask(){
        weak var weakSelf = self
        LGTRWZCommenAlert.CommenAlertalertShow(title: "温馨提示", desc: "您确定要放弃此任务单吗？", subText: "", sureTitle: "确认", cancelTitle: "取消", sureBlock: {
            weakSelf?.giveupAction()
        }, cancelBlock: {
            
        }, currentVC: self.navigationController!)
    }
    
    //放弃任务请求
    func giveupAction(){
        let param:Dictionary<String, Any> = ["id": self.orderModel?.id ?? 0, "status": 2]
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_OrderStatus_Update_URL, param: param, showMessage:true, success: { (json) in
            weakSelf?.dataChange(json: json)
        }) { (json) in
            
        }
    }
    
    //提交任务
    func submitTask(){
        //判断
        for  i in 0..<self.stepArray.count{
            let dict = self.stepArray[i]
            let key:String = "\(i + 1)"
            let type = dict["type"] as? Int ?? 0
            let info = self.orderSubmitInfo[key]
            if type == 6{
                if info == nil{
                    WisdomHUD.showError(text: "请按要求输入文字内容")
                    return
                }
            }
            if type == 5{
                if info == nil{
                    WisdomHUD.showError(text: "请上传验证图")
                    return
                }
            }
            
        }
        weak var weakSelf = self
        LGTRWZCommenAlert.CommenAlertalertShow(title: "温馨提示", desc: "您确定要提交此任务单吗？", subText: "", sureTitle: "确认", cancelTitle: "取消", sureBlock: {
            weakSelf?.submitAction()
        }, cancelBlock: {
            
        }, currentVC: self.navigationController!)
    }
    
    func submitAction(){
        var param:Dictionary<String, Any> = [:]
        var imageStr:String = ""
        for info in self.orderSubmitInfo{
            if info.value is String{
                param["message"] = info.value as? String ?? ""
            }
            else if info.value is Dictionary<String, Any>{
                let imageInfo:Dictionary<String, Any> = info.value as! Dictionary<String, Any>
                let id:Int = imageInfo["id"] as? Int ?? -1
                if id != -1{
                    imageStr.append("\(id),")
                }
            }
        }
        
        param["image"] = imageStr
        param["id"] = self.orderModel?.id
        param["status"] = 4
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_OrderStatus_Update_URL, param: param, showMessage: true, success: { (json) in
            weakSelf?.orderSubmitInfo = [:]
            weakSelf?.dataChange(json: json)
        }) { (json) in
        }
    }
    
    //申请任务
    func applyTask(){
        weak var weakSelf = self
        LGTRWZCommenAlert.CommenAlertalertShow(title: "温馨提示", desc: "确认申请做此单任务吗？", subText: "", sureTitle: "确认", cancelTitle: "取消", sureBlock: {
            weakSelf?.applyTaskAction()
        }, cancelBlock: {
            
        }, currentVC: self.navigationController!)
    }
    
    func applyTaskAction(){
        let taskID:Int = self.taskModel?.id ?? 0
        let param:Dictionary<String, Any> = ["id":taskID]
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_Order_Apply_URL, param: param, showMessage: true, success: { (json) in
            //weakSelf?.dataChange(json: json)
            //跳转订单详情
            let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let detailVC:LGTPostDetailVC = LGTPostDetailVC()
            var orderModel:TaskOrderModel = TaskOrderModel()
            orderModel.id = data["id"] as? Int ?? 0
            detailVC.viewDetailType = .LLZ_OrderView_Type
            detailVC.orderModel = orderModel
            
//            var vcArray:Array<UIViewController> = weakSelf?.navigationController?.viewControllers ?? []
//            vcArray.removeLast()
//            vc:UIViewController = vcArray[0]
            weakSelf?.navigationController?.pushViewController(detailVC, animated: false)
            
        }) { (json) in
            
        }
    }
    
    //追加
    func appendAction(){
        //发布参数获取
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Post_Param_URL, param: [:], success: { (json) in
            let model = try! lgtDecode(PostParamModel.self, param: (json["data"] as! [String : Any]))
            let vc:LGTRWZAppendTaskVC = LGTRWZAppendTaskVC()
            vc.paramModel = model
            vc.submitInfo = weakSelf?.submitDataInfo2
            vc.modalPresentationStyle = .overCurrentContext
            weakSelf?.navigationController?.present(vc, animated: false, completion: nil)
        }) { (json) in
            
        }
    }
    
    //status (integer, optional): 状态[1-审核中,2-未通过,3-派发中,4-暂停中,5-已撤回,6-已过期,7-已完成,8-已下架] ,
    func lookPrice(){
        let vc:LGTLookPriceAlert = LGTLookPriceAlert()
        vc.modalPresentationStyle = .overCurrentContext
        vc.taskInfo = self.infoData
        self.navigationController?.present(vc, animated: false, completion: nil)
    }
    
    //状态修改
    func updateTaskStatues(status:Int){
        weak var weakSelf = self
        var desc:String = ""
        var subText:String = ""
        if status == 5{
            desc = "您确定要撤回此任务单吗？"
            subText = "撤回后未被申请的任务金额将返回你的钱包 平台将不再展示该任务"
        }else if status == 3{
            desc = "您确定要继续此任务单吗？"
        }else if status == 4{
            desc = "您确定要暂停此任务单吗？"
        }
        
        LGTRWZCommenAlert.CommenAlertalertShow(title: "温馨提示", desc: desc, subText: subText, sureTitle: "确认", cancelTitle: "取消", sureBlock: {
            weakSelf?.postTaskStatues(status: status)
        }, cancelBlock: {
            
        }, currentVC: self.navigationController!)
    }
    
    func postTaskStatues(status:Int){
        let param = ["status":status,
                     "id": self.taskModel?.id ?? 0]
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Statues_Update_URL, param: param, success: { (json) in
            weakSelf?.dataChange(json: json)
        }) { (json) in
            
        }
    }
    
    func showFooterMoreView(){
        if self.footMoreView == nil{
            self.footMoreView = UIView.init()
            self.footMoreView?.backgroundColor = UIColor.white
            self.footMoreView?.layer.borderColor = GrayColor.cgColor
            self.footMoreView?.layer.borderWidth = 1
            self.view.addSubview(self.footMoreView!)
            self.footMoreView?.isHidden = true
            self.footMoreView?.snp.makeConstraints({ (make) in
                make.width.equalTo(SizeFitFloat(100))
                make.height.equalTo(SizeFitFloat(81))
                make.bottom.equalTo(-TabBarH)
                make.left.equalTo(SizeFitFloat(9))
            })
            
            let rebackBtn:UIButton = LGTViewCreateUtil.share.createButtonTitleAndImage(imageName: "withdraw", title: "撤回", color:TextColor, font: Font_Normal_18, backColor: UIColor.white)
            self.footMoreView!.addSubview(rebackBtn)
            rebackBtn.snp.makeConstraints { (make) in
                make.left.right.top.equalTo(SizeFitFloat(0))
                make.height.equalTo(SizeFitFloat(40))
            }
            
            let lookBtn:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "查看单价", font: Font_Normal_18, color: TextColor, selectedColor: TextColor)
            self.footMoreView?.addSubview(lookBtn)
            lookBtn.snp.makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(SizeFitFloat(40))
                make.height.equalTo(SizeFitFloat(40))
            }

            rebackBtn.tag = LGTRWZDetailBtnType.RebackBtnType.rawValue
            rebackBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)
            lookBtn.tag = LGTRWZDetailBtnType.LookBtnType.rawValue
            lookBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)
        }
        self.footMoreView?.isHidden = !self.footMoreView!.isHidden
    }
}
